import React, {Component} from 'react'
import PropTypes from 'prop-types'
import {Form, Icon, Input, Button,} from "antd";
import './index.less'

// const FormItem = Form.item

const FormItem = Form.Item

class LoginForm extends Component {

  static propTypes = {
    login: PropTypes.func.isRequired
  }

  handleSubmit = (e)=>{
    e.preventDefault()
    const {form} = this.props
    form.validateFields((err,values)=>{
      if(!err){
        const values = this.props.form.getFieldsValue()
        //const {username,password} = this.props.form.getFieldsValue()
        // console.log(values)
        console.log('SendAjax')
        this.props.login(values)
      }else{
        return alert('Please re-enter')
      }
    })
  }
  validatePwd = (rule,value,callback)=>{
    /*2. 密码必须输入,长度必须是4到8位*/
    value = value.trim()
    if(value===''){
      callback('Please enter password')
    }else if(value.length<4 || value.length>8){
      callback('You need to enter 4~8 characters')
    }else{
      callback()
    }
  }
  render() {
    const {getFieldDecorator} = this.props.form
    return (
      <Form className='login-form' onSubmit={this.handleSubmit}>
        <FormItem>
          {/*1. 用户名必须输入长度不能小于4*/}
          {
            getFieldDecorator(
              'username',
              {
                initialValue: 'admin',
                rules:[{
                  required: true,
                  min: 4,
                  whitespace: true
                }]
              })(
                <Input prefix={<Icon type="user" style={{color: 'rgba(0,0,0,.25)'}}/>} placeholder="Username"/>
              )
          }
        </FormItem>
        <FormItem>
          {/*2. 密码必须输入,长度必须是4到8位*/}
          {
            getFieldDecorator(
              'password',
              {
                initialValue: '',
                rules: [{validator:this.validatePwd}]
              })(
                <Input type='password' prefix={<Icon type="clock-circle" style={{color: 'rgba(0,0,0,.25)'}}/>} placeholder="Password"/>
              )
          }
        </FormItem>
        <FormItem>
          <Button type="primary" htmlType="submit" className="login-form-button">Click to Login</Button>
        </FormItem>
      </Form>
    )
  }
}

export default Form.create()(LoginForm) //此时LoginForm组件就有了this.props.form属性，从而有了相关的API，比如getFieldDecorator等
